<?php

namespace Biz\service\brand;

use Biz\cache\wiki\WikiRanking as cacheWikiRanking;
use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\model\brandActivity\BrandActivityBasic;
use Biz\model\GoodsTestActivity\FineGoodsModel;
use Biz\model\NewProduct\NewProductWikiModel;
use Biz\service\wikiRanking\Ranking;
use Biz\tools\helper\Common;
use Doraemon\service\Dynamic;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;

class BrandActivity
{
    /**
     * 获取品牌活动信息
     * @param $brandId
     * @return array
     */
    public static function getBrandActivityInfo($brandId)
    {
        $info = [];
        $list = BrandActivityBasic::getActivityByBrandIds($brandId);
        foreach ($list as $row) {
            if ($info) {
                break;
            }
            if ($row['activity_type'] == BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX) {
                $info = self::getBlindBoxInfo($brandId);
            } else if ($row['activity_type'] == BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT) {
            } else if ($row['activity_type'] == BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST) {
                $info = self::getGoodsTestInfo($brandId);
            }
        }
        return $info;
    }

    private static function getBlindBoxInfo($brandId)
    {
        $now = time();
        $where = [
            'activity_type' => mBlindBoxActivity::ACTIVITY_TYPE_BLIND_BOX,
            'prize_type' => [mBlindBoxActivity::PRIZE_TYPE_GOODS, mBlindBoxActivity::PRIZE_TYPE_GOOD_COUPON],
            'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
            //'prize_stock[>]' => 0,
            'start_time[<=]' => $now,
            'end_time[>=]' => $now,
            'brand_id' => $brandId,
        ];
        $blindBoxActivityInfo = mBlindBoxActivity::getByWhere($where);
        $info = self::formatInfo(BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX, $blindBoxActivityInfo);
        return $info;
    }

    private static function getGoodsTestInfo($brandId)
    {
        $now = time();
        $where = [
            'activity_state' => FineGoodsModel::STATE_PASS,
            'schedule_start_time[<=]' => $now,
            'schedule_end_time[>=]' => $now,
            'brand_id' => $brandId,
        ];
        $fineGoodsInfo = FineGoodsModel::first($where);
        $info = self::formatInfo(BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST, $fineGoodsInfo);
        return $info;
    }

    private static function formatInfo($activityType, $activityInfo)
    {
        $info = [];
        if ($activityType && $activityInfo) {
            switch ($activityType) {
                case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                    $info = [
                        'id' => $activityInfo['id'],
                        'title' => '抽奖进行中，快来参加吧～',
                        'prize_title' => $activityInfo['prize_title'],
                        'prize_price' => $activityInfo['prize_price'],
                        'prize_img' => $activityInfo['prize_img'],
                        'link' => self::getActivityUrl($activityType),
                        'bg_img' => 'https://img.haohaozhu.cn/Op-imageShow/f507b308905u0pJ00qvrbsb?iv=1',
                        'tips_suffix' => '正在抽奖',
                    ];
                    break;
                case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                    $info = [
                        'id' => $activityInfo['id'],
                        'title' => '好好测进行中，快来免费申请吧~',
                        'prize_title' => $activityInfo['basic_title'],
                        'prize_price' => $activityInfo['goods_worth'],
                        'prize_img' => $activityInfo['cover_img_url'],
                        'link' => self::getActivityUrl($activityType, $activityInfo['id']),
                        'bg_img' => 'https://img.haohaozhu.cn/Op-imageShow/43f0e308605u0xs00rd7dwz?iv=1',
                        'tips_suffix' => '正在免费申领',
                    ];
                    break;
            }
        }
        return $info;
    }

    /**
     * 创建品牌活动中奖动态
     * @param $uid
     * @param $activityId
     * @param $activityType
     */
    public static function createDynamic($uid, $activityId, $activityType)
    {
        $data = ['activity_id' => $activityId, 'activity_type' => $activityType];
        $activityInfo = BrandActivityBasic::getByWhere(['activity_id' => $activityId, 'activity_type' => $activityType, 'activity_state' => BrandActivityBasic::ACTIVITY_STATE_NORMAL]);
        if (!empty($activityInfo) && $activityInfo['id']) {
            Dynamic::postBrandActivity($uid, $activityInfo['id'], $data);
        }
    }

    /**
     * 获取品牌活动的中奖动态信息
     * @param $ids
     * @return array
     */
    public static function getBrandActivityForDynamic($ids)
    {
        $list = BrandActivityBasic::getActivityByIds($ids);
        $blindBoxIds = [];
        $newProductIds = [];
        $goodsTestIds = [];
        $listArr = [];
        foreach ($list as $row) {
            switch ($row['activity_type']) {
                case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                    $blindBoxIds[] = $row['activity_id'];
                    break;
                case BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT:
                    $newProductIds[] = $row['activity_id'];
                    break;
                case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                    $goodsTestIds[] = $row['activity_id'];
                    break;
            }
            $listArr[$row['id']] = $row['activity_id'] . '_' . $row['activity_type'];
        }
        $blindBoxInfos = $blindBoxIds ? mBlindBoxActivity::selectByWhere(['id' => $blindBoxIds, 'dynamic_img[!]' => ''], ['id', 'dynamic_img']) : [];
        $blindBoxInfos = array_column($blindBoxInfos, 'dynamic_img', 'id');
        $newProductInfos = $newProductIds ? NewProductWikiModel::all(['id' => $newProductIds, 'dynamic_img[!]' => ''], ['id', 'dynamic_img']) : [];
        $newProductInfos = array_column($newProductInfos, 'dynamic_img', 'id');
        $goodTestInfos = $goodsTestIds ? FineGoodsModel::pluck(['id' => $goodsTestIds, 'dynamic_img[!]' => ''], ['id', 'dynamic_img']) : [];
        $goodTestInfos = array_column($goodTestInfos, 'dynamic_img', 'id');
        $result = [];
        foreach ($ids as $id) {
            if (isset($listArr[$id])) {
                $arrStr = $listArr[$id];
                $arr = explode('_', $arrStr);
                $activityId = $arr[0];
                $activityType = $arr[1];
                $dynamicImg = '';
                $link = '';
                switch ($activityType) {
                    case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                        if (isset($blindBoxInfos[$activityId])) {
                            $dynamicImg = self::getActivityDynamicImg($activityType, $blindBoxInfos[$activityId]);
                            $link = self::getActivityUrl($activityType);
                        }
                        break;
                    case BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT:
                        if (isset($newProductInfos[$activityId])) {
                            $dynamicImg = self::getActivityDynamicImg($activityType, $newProductInfos[$activityId]);
                            $link = self::getActivityUrl($activityType);
                        }
                        break;
                    case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                        if (isset($goodTestInfos[$activityId])) {
                            $dynamicImg = self::getActivityDynamicImg($activityType, $goodTestInfos[$activityId]);
                            $link = self::getActivityUrl($activityType, null, 'dynamic');
                        }
                        break;
                }
                if ($dynamicImg && $link) {
                    $result[$id] = [
                        'activity_id' => $activityId,
                        'activity_type' => $activityType,
                        'cover_img' => $dynamicImg,
                        'link' => $link
                    ];
                }
            }
        }
        return $result;
    }

    /**
     * 获取品牌活动的链接
     * @param $activityType
     * @param $activityId
     * @return string
     */
    public static function getActivityUrl($activityType, $activityId = null, $scene = '')
    {
        $link = '';
        switch ($activityType) {
            case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                $link = self::getBlindBoxLink();
                $link = LinkFormat::encryptionLink($link);
                break;
            case BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT:
                $link = self::getNewProductLink();
                $link = LinkFormat::encryptionLink($link);
                break;
            case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                $link = self::getFindGoodsTestLink($activityId);
                if ($scene == 'dynamic') {
                    $link = Common::formatFullScreenLink($link);
                } else {
                    $link = LinkFormat::encryptionLink($link);
                }
                break;
        }
        return $link;
    }

    public static function getActivityDynamicImg($activityType, $dynamicId)
    {
        $dynamicImg = '';
        switch ($activityType) {
            case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                $dynamicImg = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $dynamicId, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                break;
            case BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT:
                $dynamicImg = ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $dynamicId, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                break;
            case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                $dynamicImg = ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $dynamicId, ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                break;
        }
        return $dynamicImg;
    }

    /**
     * 盲盒
     * @return string
     */
    public static function getBlindBoxLink(): string
    {
        return Hhzurl::getDomain() . '/brand/blind-box?hhzjump=1';
    }

    /**
     * 新品速递
     * @return string
     */
    public static function getNewProductLink(): string
    {
        return Hhzurl::getDomain() . '/brand/new-product-express';
    }

    /**
     * 好物轻测
     * @param $activityId
     * @return string
     */
    public static function getFindGoodsTestLink($activityId): string
    {
        if (!is_null($activityId)) {
            $url = Hhzurl::getDomain() . '/brand/light-test/detail?id=' . $activityId;
        } else {
            $url = Hhzurl::getDomain() . '/brand/light-test/home';
        }
        return $url;
    }

    /**
     * 服务平台查询正在活动中的商品
     * @param $basicIds
     * @return array
     */
    public static function bGetWikiBasicActivity($basicIds)
    {
        $result = [];

        $activityBasic = $basicIds ? BrandActivityBasic::getLimitActivityByBasicIds($basicIds) : [];
        $now = time();
        foreach ($activityBasic as $row) {
            switch ($row['activity_type']) {
                case BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX:
                case BrandActivityBasic::ACTIVITY_TYPE_NEW_PRODUCT:
                    if ($row['end_time'] >= $now) {
                        $result[$row['basic_id']][] = [
                            'activity_type' => $row['activity_type'],
                            'start_time' => $row['start_time'],
                            'end_time' => $row['end_time']
                        ];
                    }
                    break;
                case BrandActivityBasic::ACTIVITY_TYPE_LIGHT_TEST:
                    if (($row['end_time'] + FineGoodsModel::VERIFY_USER_TIME) >= $now) {//申请中、名单审核中的好物亲测
                        $result[$row['basic_id']][] = [
                            'activity_type' => $row['activity_type'],
                            'start_time' => $row['start_time'],
                            'end_time' => $row['end_time'] + FineGoodsModel::VERIFY_USER_TIME
                        ];
                    }
                    break;
            }
        }

        $rankingDay = Ranking::getRankingDay();
        $hotRankingArr = $basicIds ? cacheWikiRanking::getHotRankingByBasicIds($rankingDay, $basicIds) : [];
        $publicPraiseRankingArr = $basicIds ? cacheWikiRanking::getPublicPraiseRankingByBasicIds($rankingDay, $basicIds) : [];

        foreach ($basicIds as $basicId) {
            if ($hotRankingArr[$basicId] || $publicPraiseRankingArr[$basicId]) {
                $result[$basicId][] = [
                    'activity_type' => BrandActivityBasic::ACTIVITY_TYPE_WIKI_RANKING,//榜单，虚拟活动type（仅品牌平台商品列表使用）
                    'start_time' => strtotime($rankingDay),
                    'end_time' => strtotime('+7 days', strtotime($rankingDay)) - 1
                ];
            }
        }
        return $result;
    }
}
